<?php

namespace common\models\trade;

use Yii;
use Alipay\aop\request\alipay\TradeRequest;
use common\helpers\IpHelper;
use common\helpers\Url;

/**
 * This is the model class for table "{{%trade}}".
 */
class UnifiedPayment extends Trade {

    const NOTIFY_CALLBACK_URL = 'http://paymch.oppoedu.com/notify/';

    public function getAlipay() {
        if ($this->paymode !== static::PAYMODE_ALIPAY) {
            return '';
        }
        $requestName = TradeRequest::REQUEST_APP_PAY;
        $request = new TradeRequest($requestName);
        $bizContent = [
            'out_trade_no' => $this->trade_no,
            'total_amount' => $this->cash,
            'subject' => $this->subject,
            'body' => $this->body,
            'timeout_express' => '15m',
            'notify_url' => $this->getNotifyUrl(),
            'time_expire' => date('Y-m-d H:i', $this->expire_time),
        ];
        $request->setBizContent($bizContent);
        $response = Yii::$app->alipay->sdkExecute($request);
        return $response; //htmlspecialchars($response);
    }

    public function getWechat() {
        if ($this->paymode !== static::PAYMODE_WECHAT) {
            return [];
        }
        $total = (int) ($this->cash * 100);
        if ($total <= 0) {
            return [];
        }
        $attributes = [
            'body' => Yii::$app->name . '-' . $this->subject,
            'detail' => $this->body,
            'out_trade_no' => $this->trade_no,
            'total_fee' => $total,
            'spbill_create_ip' => IpHelper::ip(false),
            'notify_url' => $this->getNotifyUrl(),
            'time_expire' => date('YmdHis', $this->expire_time),
        ];
        $wechatPay = null;
        if ($this->partner_id == 1) {
            $attributes['trade_type'] = 'APP';
            $wechatPay = Yii::$app->wxpay;
        } elseif ($this->partner_id == 2) {
            $openid = $this->getOpenid();
            Yii::error($openid);
            if ($openid == null) {
                Yii::error('需要openid');
                return [];
            }
            $attributes['trade_type'] = 'JSAPI';
            $attributes['openid'] = $openid;
            $wechatPay = Yii::$app->mppay;
        } else {
            return [];
        }
        
        Yii::error($attributes);

        return $wechatPay->prepay($attributes);
    }

    public function getNotifyUrl() {
        return Url::toRemote($this->paymode, self::NOTIFY_CALLBACK_URL);
    }

    public function getOpenid() {
        if ($this->connectUser) {
            return $this->connectUser->openid;
        }
        return null;
    }

    public function fields() {
        return [
            'id',
            'paymode' => function() {
                return (string) $this->paymode;
            },
            'wechat',
            'alipay',
        ];
    }

}
